import fetch from 'node-fetch';
import EventSource from 'eventsource';

const SERVER_URL = 'http://localhost:3000';

// 测试SSE连接
function testSSEConnection() {
  console.log('🔗 测试SSE连接...');
  
  const eventSource = new EventSource(`${SERVER_URL}/sse`);
  
  eventSource.onopen = () => {
    console.log('✅ SSE连接已建立');
  };
  
  eventSource.onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log('📨 收到SSE消息:', data);
  };
  
  eventSource.onerror = (error) => {
    console.error('❌ SSE连接错误:', error);
  };
  
  // 5秒后关闭连接
  setTimeout(() => {
    eventSource.close();
    console.log('🔌 SSE连接已关闭');
  }, 5000);
  
  return eventSource;
}

// 测试MCP工具调用
async function testMCPTools() {
  console.log('\n🛠️  测试MCP工具...');
  
  // 测试获取工具列表
  try {
    const listToolsRequest = {
      jsonrpc: '2.0',
      id: 1,
      method: 'tools/list'
    };
    
    console.log('📋 获取工具列表...');
    const listResponse = await fetch(`${SERVER_URL}/mcp`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(listToolsRequest),
    });
    
    const listResult = await listResponse.json();
    console.log('✅ 可用工具:', listResult.result?.tools?.map(t => t.name));
    
    // 测试回显工具
    console.log('\n🔄 测试回显工具...');
    const echoRequest = {
      jsonrpc: '2.0',
      id: 2,
      method: 'tools/call',
      params: {
        name: 'echo',
        arguments: {
          text: '你好，MCP世界！'
        }
      }
    };
    
    const echoResponse = await fetch(`${SERVER_URL}/mcp`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(echoRequest),
    });
    
    const echoResult = await echoResponse.json();
    console.log('✅ 回显结果:', echoResult.content?.[0]?.text);
    
    // 测试时间工具
    console.log('\n⏰ 测试时间工具...');
    const timeRequest = {
      jsonrpc: '2.0',
      id: 3,
      method: 'tools/call',
      params: {
        name: 'get_current_time',
        arguments: {}
      }
    };
    
    const timeResponse = await fetch(`${SERVER_URL}/mcp`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(timeRequest),
    });
    
    const timeResult = await timeResponse.json();
    console.log('✅ 时间结果:', timeResult.content?.[0]?.text);
    
    // 测试计算工具
    console.log('\n🧮 测试计算工具...');
    const calcRequest = {
      jsonrpc: '2.0',
      id: 4,
      method: 'tools/call',
      params: {
        name: 'calculate',
        arguments: {
          expression: '2 + 3 * 4'
        }
      }
    };
    
    const calcResponse = await fetch(`${SERVER_URL}/mcp`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(calcRequest),
    });
    
    const calcResult = await calcResponse.json();
    console.log('✅ 计算结果:', calcResult.content?.[0]?.text);
    
  } catch (error) {
    console.error('❌ MCP测试失败:', error.message);
  }
}

// 测试健康检查
async function testHealthCheck() {
  console.log('\n❤️  测试健康检查...');
  
  try {
    const response = await fetch(`${SERVER_URL}/health`);
    const result = await response.json();
    console.log('✅ 服务器状态:', result);
  } catch (error) {
    console.error('❌ 健康检查失败:', error.message);
  }
}

// 主测试函数
async function runTests() {
  console.log('🚀 开始测试MCP SSE服务器...\n');
  
  // 首先检查服务器是否运行
  try {
    const response = await fetch(`${SERVER_URL}/health`);
    const info = await response.json();
    console.log('ℹ️  服务器状态:', info);
  } catch (error) {
    console.error('❌ 无法连接到服务器，请确保服务器正在运行');
    console.log('💡 运行命令: npm start');
    return;
  }
  
  // 测试SSE连接
  const eventSource = testSSEConnection();
  
  // 等待SSE连接建立后测试MCP功能
  setTimeout(async () => {
    await testMCPTools();
    await testHealthCheck();
    
    console.log('\n✨ 所有测试完成！');
    process.exit(0);
  }, 2000);
}

// 运行测试
runTests().catch(console.error); 